﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarInfor.DAL;
using System.Diagnostics;

namespace CarInfor.UI
{
    public partial class frmSendMsg : Form
    {
        MsgType curMsgType;
        string idsForSql = string.Empty;

        List<string> VarYearCheckDic = new List<string>();
        List<string> VarInsuranceFormDic = new List<string>();

        /// <summary>
        /// 初始化字典
        /// </summary>
        void InitDic()
        {
            VarYearCheckDic.Add("<%年检信息.车主姓名%>");
            VarYearCheckDic.Add("<%年检信息.车辆号牌%>");
            VarYearCheckDic.Add("<%年检信息.到期日期%>");

            VarInsuranceFormDic.Add("<%保险信息.被保险人%>");
            VarInsuranceFormDic.Add("<%保险信息.车辆号牌%>");
            VarInsuranceFormDic.Add("<%保险信息.交强险到期日期%>");
            VarInsuranceFormDic.Add("<%保险信息.商业险到期日期%>");
        }


        public frmSendMsg(MsgType mt, string ids)
        {
            InitializeComponent();
            InitDic();

            curMsgType = mt;
            idsForSql = ids;
            if (curMsgType == MsgType.Insurance)
            {
                this.Text += "--保险客户";
                this.年检信息ToolStripMenuItem1.Visible = false;
            }
            else if (curMsgType == MsgType.Yearcheck)
            {
                this.Text += "--年检客户";
                this.保险信息ToolStripMenuItem1.Visible = false;
            }
            Bind();
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        private void Bind()
        {
            this.listView1.Items.Clear();
            if (curMsgType == MsgType.Insurance)
            {
                string sql = " id in (" + idsForSql + ") and Telephone is not null and Telephone<>''";
                InsuranceForm insuranceForm = new InsuranceForm();
                DataTable dt = insuranceForm.Query(sql);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListViewItem lvi = new ListViewItem((i + 1).ToString());
                    Dictionary<string, string> inforDic = new Dictionary<string, string>();
                    inforDic.Add("<%保险信息.被保险人%>", dt.Rows[i]["被保险人"].ToString());
                    inforDic.Add("<%保险信息.车辆号牌%>", dt.Rows[i]["车辆号牌"].ToString());
                    inforDic.Add("<%保险信息.交强险到期日期%>", string.IsNullOrEmpty(dt.Rows[i]["交强险到期日期"].ToString()) ? "" : DateTime.Parse(dt.Rows[i]["交强险到期日期"].ToString()).ToString("yyyy年M月d日"));
                    inforDic.Add("<%保险信息.商业险到期日期%>", string.IsNullOrEmpty(dt.Rows[i]["商业险到期日期"].ToString()) ? "" : DateTime.Parse(dt.Rows[i]["商业险到期日期"].ToString()).ToString("yyyy年M月d日"));
                    lvi.Tag = inforDic;
                    lvi.SubItems.Add(dt.Rows[i]["联系电话"].ToString());
                    lvi.SubItems.Add(dt.Rows[i]["被保险人"].ToString());
                    this.listView1.Items.Add(lvi);
                }
            }
            else if (curMsgType == MsgType.Yearcheck)
            {
                string sql = " id in (" + idsForSql + ") and Telephone is not null and Telephone<>''";
                YearCheck yearCheck = new YearCheck();
                DataTable dt = yearCheck.Query(sql);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ListViewItem lvi = new ListViewItem((i + 1).ToString());
                    Dictionary<string, string> inforDic = new Dictionary<string, string>();
                    inforDic.Add("<%年检信息.车主姓名%>", dt.Rows[i]["车主姓名"].ToString());
                    inforDic.Add("<%年检信息.车辆号牌%>", dt.Rows[i]["车辆号牌"].ToString());
                    inforDic.Add("<%年检信息.到期日期%>", string.IsNullOrEmpty(dt.Rows[i]["到期日期"].ToString()) ? "" : DateTime.Parse(dt.Rows[i]["到期日期"].ToString()).ToString("yyyy年M月d日"));
                    lvi.Tag = inforDic;
                    lvi.SubItems.Add(dt.Rows[i]["联系电话"].ToString());
                    lvi.SubItems.Add(dt.Rows[i]["车主姓名"].ToString());
                    this.listView1.Items.Add(lvi);
                }
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDele_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count != 0)
            {
                this.listView1.Items.Remove(this.listView1.SelectedItems[0]);
                for (int i = 0; i < this.listView1.Items.Count; i++)
                {
                    this.listView1.Items[i].SubItems[0].Text = (i + 1).ToString();
                }
            }
            else
            {
                MessageHelper.ShowInfo("请选择要删除的电话号码！");
            }


        }

        /// <summary>
        /// 语法检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtMsg.Text.Trim()))
            {
                MessageHelper.ShowInfo("请输入短信内容！");
                return;
            }

            if (!CheckInput())
            {
                MessageHelper.ShowInfo("语法有误！");
            }
            else
            {
                MessageHelper.ShowInfo("语法正确！");
            }
        }

        /// <summary>
        /// 获取变量
        /// </summary>
        /// <returns></returns>
        private List<string> GetVar()
        {
            List<string> lst = new List<string>();
            if (curMsgType == MsgType.Yearcheck)
            {
                foreach (var item in VarYearCheckDic)
                {
                    if (this.txtMsg.Text.IndexOf(item) > -1)
                    {
                        lst.Add(item);
                    }
                }
            }
            else if (curMsgType == MsgType.Insurance)
            {
                foreach (var item in VarInsuranceFormDic)
                {
                    if (this.txtMsg.Text.IndexOf(item) > -1)
                    {
                        lst.Add(item);
                    }
                }
            }
            return lst;
        }

        /// <summary>
        /// 获取短信(切分短信)
        /// </summary>
        /// <returns></returns>
        private List<string> GetMsg(string msg)
        {
            List<string> lst = new List<string>();
            if (msg.Length <= 70)
            {
                lst.Add(msg);
            }
            else
            {
                int limit = 60;//每条限制 
                int total = msg.Length;//字数
                int count = total / limit;//条数
                int mod = total % limit;//最后一条字数
                if (mod > 0)
                {
                    count++;
                }
                for (int i = 0; i < count; i++)
                {
                    string str = string.Empty;
                    if (mod > 0 && i == count - 1)
                    {
                        str = string.Format("({0}/{1}){2}", i + 1, count, msg.Substring(i * limit));
                    }
                    else
                    {
                        str = string.Format("({0}/{1}){2}", i + 1, count, msg.Substring(i * limit, limit));
                    }
                    lst.Add(str);
                }
            }
            return lst;

        }
        /// <summary>
        /// 生成预览
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                MessageHelper.ShowInfo("语法有误！");
                return;
            }

            this.listView2.Items.Clear();
            if (this.txtMsg.Text.Trim() == "")
            {
                MessageHelper.ShowInfo("请输入短信内容!");
                return;
            }

            int count = 0;//计数
            var lst = GetVar();
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                string msg = this.txtMsg.Text;
                if (lst.Count > 0)
                {
                    var Dic = listView1.Items[i].Tag as Dictionary<string, string>;
                    foreach (string item in lst)
                    {
                        msg = msg.Replace(item, Dic[item]);
                    }
                }
                List<string> msgLst = GetMsg(msg);
                for (int j = 0; j < msgLst.Count; j++)
                {
                    count++;
                    ListViewItem lvi = new ListViewItem(count.ToString());
                    lvi.SubItems.Add(listView1.Items[i].SubItems[2].Text);
                    lvi.SubItems.Add(listView1.Items[i].SubItems[1].Text);
                    lvi.SubItems.Add(msgLst[j]);
                    this.listView2.Items.Add(lvi);
                }
            }
        }

        /// <summary>
        /// 语法检查
        /// </summary>
        /// <returns></returns>
        bool CheckInput()
        {
            bool falg = true;
            if (curMsgType == MsgType.Yearcheck)
            {
                if (this.txtMsg.Text.IndexOf("<%") > -1 || this.txtMsg.Text.IndexOf("%>") > -1)
                {
                    bool mark = false;
                    foreach (var item in VarYearCheckDic)
                    {
                        if (this.txtMsg.Text.IndexOf(item) > -1)
                        {
                            mark = true;
                            break;
                        }
                    }

                    if (!mark)
                    {
                        return false;
                    }

                    foreach (var item in VarInsuranceFormDic)
                    {
                        if (this.txtMsg.Text.IndexOf(item) > -1)
                        {
                            falg = false;
                            break;
                        }
                    }
                }
            }
            else if ((curMsgType == MsgType.Insurance))
            {
                if (this.txtMsg.Text.IndexOf("<%") > -1 || this.txtMsg.Text.IndexOf("%>") > -1)
                {
                    bool mark = false;
                    foreach (var item in VarInsuranceFormDic)
                    {
                        if (this.txtMsg.Text.IndexOf(item) > -1)
                        {
                            mark = true;
                            break;
                        }
                    }

                    if (!mark)
                    {
                        return false;
                    }

                    foreach (var item in VarYearCheckDic)
                    {
                        if (this.txtMsg.Text.IndexOf(item) > -1)
                        {
                            falg = false;
                            break;
                        }
                    }
                }
            }
            return falg;
        }

        /// <summary>
        /// 输入字符数统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMsg_TextChanged(object sender, EventArgs e)
        {
            this.lblWordCount.Text = string.Format("你已经输入了{0}个字符。", this.txtMsg.Text.Length);
        }

        #region 插入变量

        private void 车主姓名ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 车辆号牌ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 到期日期ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 被保险人ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 车辆号牌ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 交强险到期日期ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        private void 商业险到期日期ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            txtMsg.Text = txtMsg.Text.Insert(txtMsg.SelectionStart, (sender as ToolStripMenuItem).Tag.ToString());
            this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
        }

        #endregion

        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 立即发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (this.listView2.Items.Count == 0)
            {
                MessageHelper.ShowInfo("请先生成短信预览！");
                return;
            }

            if (Common.IsProcessRunByName("GSms"))
            {
                MessageHelper.ShowInfo("请先退出短信猫软件，再试！");
                return;
            }

            if (MessageHelper.ShowYesNoChoice("你确定立即发送列表中的" + this.listView2.Items.Count.ToString() + "条短信吗？") == DialogResult.Yes)
            {
                try
                {
                    for (int i = 0; i < listView2.Items.Count; i++)
                    {
                        MsgInterface mi = new MsgInterface();
                        //注意：短信猫以下字段不能为空字符串
                        mi.Name = listView2.Items[i].SubItems[1].Text;
                        mi.Telephone = listView2.Items[i].SubItems[2].Text;
                        mi.Content = listView2.Items[i].SubItems[3].Text;
                        mi.Insert();
                    }

                    System.Diagnostics.Process.Start(MyGlobal.SmsPath + "GSms.exe");
                    this.DialogResult = DialogResult.OK;
                }
                catch (Exception ex)
                {
                    MessageHelper.ShowFail("启动短信模块失败！错误信息为：" + ex.Message);
                }
            }
        }




        private void btnSaveTemplate_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(this.txtMsg.Text.Trim()))
            {
                MessageHelper.ShowInfo("请输入短信内容！");
                return;
            }

            try
            {
                MsgTemplate mt = new MsgTemplate();
                mt.ID = Guid.NewGuid().ToString();
                mt.Content = this.txtMsg.Text.Trim();
                mt.Insert();
                MessageHelper.ShowInfo("添加成功！");
            }
            catch (Exception ex)
            {
                MessageHelper.ShowFail("添加失败！" + ex.Message);
            }
        }

        private void btnInportByTemplate_Click(object sender, EventArgs e)
        {
            frmMsgTemplate fmt = new frmMsgTemplate();
            if (fmt.ShowDialog() == DialogResult.OK)
            {
                this.txtMsg.Text = fmt.GetSelect();
                this.txtMsg.SelectionStart = this.txtMsg.Text.Length;
            }
        }
    }
}
